package com.fellan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.content.res.Configuration;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.fellan.business.BusinessConstants;
import com.fellan.business.DataManager;
import com.fellan.model.Instanta;
import com.fellan.model.Line;
import com.fellan.model.Station;
import com.fellan.persistance.DBManager;
import com.fellan.utils.ActivityUtils;
import com.fellan.utils.DataUtils;
import com.fellan.utils.Harta;
import com.google.android.maps.GeoPoint;
import com.kankan.wheel.widget.OnWheelChangedListener;
import com.kankan.wheel.widget.OnWheelClickedListener;
import com.kankan.wheel.widget.OnWheelScrollListener;
import com.kankan.wheel.widget.WheelView;
import com.kankan.wheel.widget.adapters.ArrayWheelAdapter;
import com.makeramen.segmented.SegmentedRadioGroup;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener
{
    Instanta instantaMea = null;

    SegmentedRadioGroup segmentViewOrder;
	SegmentedRadioGroup segmentDays;
    WheelView wheel1;
    WheelView wheel2;
    WheelView wheelOrar;
    boolean wheel1Scrolling = false;
    boolean wheel2Scrolling = false;
    ArrayWheelAdapter<Line> linesAdapter;
    ArrayWheelAdapter<Station> stationsAdapter;
    ArrayWheelAdapter<Date> scheduleAdapter;

    boolean changingConfig = false;

    int orderChecked = R.id.button_linii_statii;
    int daysChecked = R.id.button_zile_lucratoare;

    int selectedWheel1 = 0;
    int selectedWheel2 = 0;
    int wheelOrarIndex=0;
    ArrayList<Line> linesList = new ArrayList<Line>();
    ArrayList<Station> stationsList = new ArrayList<Station>();
    ArrayList<Date> scheduleList = new ArrayList<Date>();

    IntentFilter receivedAllLinesSuccessIntentFilter;
    IntentFilter receivedAllStationsSuccessIntentFilter;
    IntentFilter receivedStationsForLinesSuccessIntentFilter;
    IntentFilter receivedLinesForStationsSuccessIntentFilter;
    IntentFilter receivedScheduleSuccessIntentFilter;
    
    BroadcastReceiver receivedAllLinesSuccessReceiver;
    BroadcastReceiver receivedAllStationsSuccessReceiver;
    BroadcastReceiver receivedStationsForLinesSuccessReceiver;
    BroadcastReceiver receivedLinesForStationsSuccessReceiver;
    BroadcastReceiver receivedScheduleSuccessReceiver;

    public void InitializeUI()
    {
        //Show spinning dialog
        ActivityUtils.showProgressDialog(MainActivity.this);

        restoreMe();

        changingConfig = true;


        segmentViewOrder = (SegmentedRadioGroup) findViewById(R.id.segment_vieworder);
        segmentViewOrder.setOnCheckedChangeListener(this);
        segmentViewOrder.check(orderChecked);
        segmentDays = (SegmentedRadioGroup) findViewById(R.id.segment_days);
        segmentDays.check(daysChecked);
        segmentDays.setOnCheckedChangeListener(this);

        wheel1 = (WheelView) findViewById(R.id.wheel1);
        wheel1.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                if (!wheel1Scrolling)
                {
                    selectedWheel1 = wheel1.getCurrentItem();
                    if (orderChecked == R.id.button_linii_statii)
                    {
                        showStationsForLine(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine());
                    }
                    else
                    {
                        showLinesForStation(stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                    }
                }
            }
        });
        wheel1.addClickingListener(new OnWheelClickedListener() {
            @Override
            public void onItemClicked(WheelView wheel, int itemIndex) {
                if (!wheel1Scrolling && orderChecked == R.id.button_statii_linii) {
                    Station s = DBManager.getInstance().getStationByID(stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                    DataUtils.point = new GeoPoint((int)(s.getLat()*1E6),(int)(s.getLng()*1E6));
                    DataUtils.showPoint = true;
                    Intent intent=new Intent(MainActivity.this,Harta.class);
                    startActivity(intent);
                }
            }
        });
        wheel1.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
                wheel1Scrolling = true;
                wheel2.setEnabled(false);
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                wheel1Scrolling = false;
                selectedWheel1 = wheel1.getCurrentItem();
                selectedWheel2 = 0;
                wheel2.setEnabled(true);
                if (orderChecked == R.id.button_linii_statii)
                {
                    showStationsForLine(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine());
                }
                else
                {
                    showLinesForStation(stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                }
            }
        });


        wheel2 = (WheelView) findViewById(R.id.wheel2);
        wheel2.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                if (!wheel2Scrolling)
                {
                    selectedWheel2 = wheel2.getCurrentItem();
                    if (orderChecked == R.id.button_linii_statii)
                        showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    else
                        showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                }
            }
        });
        wheel2.addClickingListener(new OnWheelClickedListener() {
            @Override
            public void onItemClicked(WheelView wheel, int itemIndex) {
                if (!wheel2Scrolling && orderChecked == R.id.button_linii_statii)
                {
                    Station s = DBManager.getInstance().getStationByID(stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    DataUtils.point = new GeoPoint((int)(s.getLat()*1E6),(int)(s.getLng()*1E6));
                    DataUtils.showPoint = true;
                    Intent intent=new Intent(MainActivity.this,Harta.class);
                    startActivity(intent);
                }
            }
        });
        wheel2.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
                wheel2Scrolling = true;
                wheel1.setEnabled(false);
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                wheel2Scrolling = false;
                selectedWheel2 = wheel2.getCurrentItem();
                wheel1.setEnabled(true);
                if (orderChecked == R.id.button_linii_statii)
                        showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    else
                        showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
            }
        });

        wheelOrar = (WheelView) findViewById(R.id.wheel_orar);
         wheelOrar.addChangingListener(new OnWheelChangedListener() {
             @Override
             public void onChanged(WheelView wheel, int oldValue, int newValue) {
                 wheelOrarIndex=wheelOrar.getCurrentItem();
             }
         });

        if (orderChecked == R.id.button_linii_statii)
            showAllLines();
        else
            showAllStations();


        changingConfig = false;

        // Hide the spinner
        ActivityUtils.hideProgressDialog(MainActivity.this);
    }

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DataUtils.setApplicationContext(getApplicationContext());

        InitializeUI();
    }

    @Override
    public Object onRetainNonConfigurationInstance()
    {
        Instanta instanta = new Instanta();
        instanta.daysChecked = daysChecked;
        instanta.orderChecked = orderChecked;
        instanta.selectedWheel1 = selectedWheel1;
        instanta.selectedWheel2 = selectedWheel2;

        return instanta;
    }

    private void restoreMe()
    {
        instantaMea = null;
        if (getLastNonConfigurationInstance() != null)
        {
            instantaMea = (Instanta)getLastNonConfigurationInstance();

            daysChecked = instantaMea.daysChecked;
            orderChecked = instantaMea.orderChecked;
            selectedWheel1 = instantaMea.selectedWheel1;
            selectedWheel2 = instantaMea.selectedWheel2;
        }
    }

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (!changingConfig)
        {
            ActivityUtils.showProgressDialog(MainActivity.this);
            if (group == segmentViewOrder) {
                orderChecked = checkedId;

                if (checkedId == R.id.button_linii_statii) {
                    selectedWheel1 = 0;
                    selectedWheel2 = 0;
                    showAllLines();
                } else if (checkedId == R.id.button_statii_linii) {
                    selectedWheel1 = 0;
                    selectedWheel2 = 0;
                    showAllStations();
                }

            } else if (group == segmentDays) {
                daysChecked = checkedId;
                if (checkedId == R.id.button_zile_lucratoare) {
                    if (orderChecked == R.id.button_linii_statii) {
                        showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    } else if (orderChecked == R.id.button_statii_linii) {
                        showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                    }
                } else if (checkedId == R.id.button_sambata) {
                    if (orderChecked == R.id.button_linii_statii) {
                        showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    } else if (orderChecked == R.id.button_statii_linii) {
                        showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                    }
                } else if (checkedId == R.id.button_duminica) {
                    if (orderChecked == R.id.button_linii_statii) {
                        showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                    } else if (orderChecked == R.id.button_statii_linii) {
                        showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                    }
                }
            }
            ActivityUtils.hideProgressDialog(MainActivity.this);
        }
	}

  /*  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.main);
        InitializeUI();
    }      */

    public void showAllLines()
    {
        if (receivedAllLinesSuccessIntentFilter == null)
            receivedAllLinesSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_ALL_LINES_RECEIVED_SUCCESSFULLY);
        if (receivedAllLinesSuccessReceiver == null)
            receivedAllLinesSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    context.unregisterReceiver(receivedAllLinesSuccessReceiver);
                    linesList = DataManager.getInstance().getAllLinesList();
                    linesAdapter = new ArrayWheelAdapter<Line>(MainActivity.this,linesList.toArray(new Line[]{}));
                    linesAdapter.setTextSize(getResources().getInteger(R.integer.wheel_head_textsize));
                    wheel1.setViewAdapter(linesAdapter);
                    wheel1.setCurrentItem(selectedWheel1);
                    if (selectedWheel1 == 0)
                    {
                        showStationsForLine(linesAdapter.getItem(selectedWheel1).getIdLine());
                    }
                }
            };
        registerReceiver(receivedAllLinesSuccessReceiver,receivedAllLinesSuccessIntentFilter);
        DataManager.getInstance().requestAllLines();
    }

    public void showAllStations()
    {
        if(receivedAllStationsSuccessIntentFilter == null)
            receivedAllStationsSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_ALL_STATIONS_RECEIVED_SUCCESSFULLY);
        if(receivedAllStationsSuccessReceiver == null)
            receivedAllStationsSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    context.unregisterReceiver(receivedAllStationsSuccessReceiver);
                    stationsList = DataManager.getInstance().getAllStationsList();
                    stationsAdapter = new ArrayWheelAdapter<Station>(MainActivity.this, stationsList.toArray(new Station[]{}));
                    stationsAdapter.setTextSize(getResources().getInteger(R.integer.wheel_head_textsize));
                    wheel1.setViewAdapter(stationsAdapter);
                    wheel1.setCurrentItem(selectedWheel1);
                    showLinesForStation(stationsAdapter.getItem(selectedWheel1).getIdStation());
                }
            };
        registerReceiver(receivedAllStationsSuccessReceiver,receivedAllStationsSuccessIntentFilter);
        DataManager.getInstance().requestAllStations();
    }

    private void showStationsForLine(int line)
    {
        if(receivedStationsForLinesSuccessIntentFilter == null)
            receivedStationsForLinesSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_STATIONS_FOR_LINE_RECEIVED_SUCCESSFULLY);
        if(receivedStationsForLinesSuccessReceiver == null)
            receivedStationsForLinesSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    context.unregisterReceiver(receivedStationsForLinesSuccessReceiver);
                    stationsList = DataManager.getInstance().getStationsForLineList();
                    stationsAdapter = new ArrayWheelAdapter<Station>(MainActivity.this, stationsList.toArray(new Station[]{}));
                    stationsAdapter.setTextSize(getResources().getInteger(R.integer.wheel_head_textsize));
                    wheel2.setViewAdapter(stationsAdapter);
                    wheel2.setCurrentItem(selectedWheel2);
                    showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(), stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
                }
            };
        registerReceiver(receivedStationsForLinesSuccessReceiver, receivedStationsForLinesSuccessIntentFilter);
        DataManager.getInstance().requestStationForLine(line);

    }

    private void showLinesForStation(int station)
    {
        if (receivedLinesForStationsSuccessIntentFilter == null)
            receivedLinesForStationsSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_LINES_FOR_STATION_RECEIVED_SUCCESSFULLY);
        if (receivedLinesForStationsSuccessReceiver == null)
            receivedLinesForStationsSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    context.unregisterReceiver(receivedLinesForStationsSuccessReceiver);
                    linesList = DataManager.getInstance().getLinesForStationList();
                    linesAdapter = new ArrayWheelAdapter<Line>(MainActivity.this, linesList.toArray(new Line[]{}));
                    linesAdapter.setTextSize(getResources().getInteger(R.integer.wheel_head_textsize));
                    wheel2.setViewAdapter(linesAdapter);
                    wheel2.setCurrentItem(selectedWheel2);
                    showSchedule(linesAdapter.getItem(wheel2.getCurrentItem()).getIdLine(), stationsAdapter.getItem(wheel1.getCurrentItem()).getIdStation());
                }
            };
        registerReceiver(receivedLinesForStationsSuccessReceiver, receivedLinesForStationsSuccessIntentFilter);
        DataManager.getInstance().requestLinesForStation(station);
    }

    private void showSchedule(int line, int station)
    {
        if (receivedScheduleSuccessIntentFilter == null)
            receivedScheduleSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_SCHEDULE_RECEIVED_SUCCESSFULLY);
        if (receivedScheduleSuccessReceiver == null)
            receivedScheduleSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    unregisterReceiver(receivedScheduleSuccessReceiver);
                    scheduleList = DataManager.getInstance().getScheduleList();
                    scheduleAdapter = new ArrayWheelAdapter<Date>(MainActivity.this,scheduleList.toArray(new Date[]{}));
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
                        scheduleAdapter.setTextSize(2*getResources().getInteger(R.integer.wheel_head_textsize));
                    else
                        scheduleAdapter.setTextSize(getResources().getInteger(R.integer.wheel_head_textsize));
                    wheelOrar.setViewAdapter(scheduleAdapter);
                    wheelOrar.setCurrentItem(getScheduleNext());
                }
            };
        registerReceiver(receivedScheduleSuccessReceiver,receivedScheduleSuccessIntentFilter);
        DataUtils.Zile ziua = null;
        switch (daysChecked)
        {
            case R.id.button_zile_lucratoare:
                ziua = DataUtils.Zile.ZILE_LUCRATOARE;
                break;
            case R.id.button_sambata:
                ziua = DataUtils.Zile.SAMBATA;
                break;
            case R.id.button_duminica:
                ziua = DataUtils.Zile.DUMINICA;
                break;
        }
        DataManager.getInstance().requestSchedule(line,station,ziua);
    }

    private int getScheduleNext()
    {
        Calendar c = Calendar.getInstance();
        c.set(1970,Calendar.JANUARY,1,c.get(Calendar.HOUR_OF_DAY),c.get(Calendar.MINUTE));

        Date d = c.getTime();
        int i=0;
        while (i<scheduleList.size() && scheduleList.get(i).getTime() < d.getTime())
            i++;
        if (i >= scheduleList.size())
            return scheduleList.size()-1;
        return i;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_activity_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch(item.getItemId()){
            case (R.id.despre):
                openAbout();
                break;
            case (R.id.hartaMare):
                openMap();
                break;
            case(R.id.trimiteMesaj):
                trimiteMesaj();
                break;
            case(R.id.hartaStatii):
                Intent intent = new Intent(MainActivity.this,Harta.class);
                startActivity(intent);
                break;
        }
        return true;
    }
    public void openAbout()
    {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(R.string.aboutTitle);
        alertDialog.setMessage(getString(R.string.about));
        alertDialog.setIcon(R.drawable.iconr);
        alertDialog.setButton(getString(R.string.Inchide), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
            }
        });
        alertDialog.setIcon(R.drawable.icon);
       alertDialog.show();
        //LocationManager locMgr  = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       /* LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = lm.getBestProvider(criteria, false);
        Location loc = lm.getLastKnownLocation(bestProvider);

        double lat = loc.getLatitude();
        double lon = loc.getLongitude();
        String geoURI = String.format("geo:%f,%f?q=memorandumului,Cluj", lat, lon);
        Uri geo = Uri.parse(geoURI);
        Intent geoMap = new Intent(Intent.ACTION_VIEW, geo);
        startActivity(geoMap);     */

    }

    public void openMap()
    {
          Intent intent=new Intent(MainActivity.this,MyWebView.class);
          startActivity(intent);
    }
    public void trimiteMesaj()
    {
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
        smsIntent.setType("vnd.android-dir/mms-sms");

        StringBuilder stringBuilder=new StringBuilder();
        if (orderChecked == R.id.button_linii_statii) {
            stringBuilder.append("Linia: ");
            stringBuilder.append(linesAdapter.getItem(wheel1.getCurrentItem()).getName());
            stringBuilder.append("\nStatia: ");
            stringBuilder.append(stationsAdapter.getItem(wheel2.getCurrentItem()).getName());
            stringBuilder.append("\n");
            //showSchedule(linesAdapter.getItem(wheel1.getCurrentItem()).getIdLine(),stationsAdapter.getItem(wheel2.getCurrentItem()).getIdStation());
        } else if (orderChecked == R.id.button_statii_linii) {
            stringBuilder.append("Linia: ");
            stringBuilder.append(linesAdapter.getItem(wheel2.getCurrentItem()).getName());
            stringBuilder.append("\nStatia:");
            stringBuilder.append(stationsAdapter.getItem(wheel1.getCurrentItem()).getName());
            stringBuilder.append("\n");
        }

        //  stringBuilder.append()
        int len=scheduleList.size();
        int cur=wheelOrarIndex;
        int ten=10;
        while(cur<len&&ten!=0)
        {
            wheel1.getCurrentItem();
            Date it = scheduleList.get(cur);
            String f = String.format("%02d", it.getHours()) + ":" + String.format("%02d", it.getMinutes());
            stringBuilder.append(f);
            stringBuilder.append("\n") ;
            cur++;
            ten--;
        }
        smsIntent.putExtra("sms_body",stringBuilder.toString());
        startActivity(smsIntent);

    }
}